/*Author: Rony Lahav (ID:043489889)*/

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;


/**
 * handles a single UDP message sending session for a single peer
 */
public class SingleUDPMessageSender implements Runnable{
	
	DBTuple tupleForSending;
	String msg;
	DatagramSocket ds = null;
	long uniqueID;
	
	public SingleUDPMessageSender(DatagramSocket soc, DBTuple tupleForSending, String message, long uniqueID) {
		this.uniqueID = uniqueID;
		this.msg=message;
		this.ds=soc;
		this.tupleForSending = tupleForSending;
	}
	
	public void run(){
		try{
			UDPSend();
		}
		catch(Exception e){}
		finally{
			final_project.removeThreadFromLivingList(uniqueID);
		}
	}
	
	/**
	 * This method creates a UDP message and sends it through the socket to the relevant peer
	 */
	public void UDPSend() {
		try {
			if (!final_project.isShutDown()){
				DatagramPacket dp = new DatagramPacket(msg.getBytes(), msg.length(), InetAddress.getByName(tupleForSending.getPeerIP()),Integer.parseInt(tupleForSending.getUdpPort()));
				ds.send(dp); // send the message to the peer
			}
		}
		catch (SocketTimeoutException e1){
			if (ds != null && !ds.isClosed()){
				ds.close();
			}
		}
		catch (IOException e2){}
	}

	public long getUniqueID(){
		return uniqueID;
	}
}
